package com.yangyouli.unity_demo_server.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSessionFactory;

import com.yangyouli.unity_demo_server.container.SqlSessionHolder;
import com.yangyouli.unity_demo_server.server.Client;

/**
 * 向每个线程的 ThreadLocal 添加或得到 SqlSession
 * @author 24279
 *
 */
public class ThreadLocalHelper {
	private static ThreadLocal<Map<SqlSessionFactory, SqlSessionHolder>> threadLocal = new ThreadLocal<>();
	private static ThreadLocal<Client> clientSockets = new ThreadLocal<>();
	
	/**
	 * 取得 SqlSession
	 * @param factory
	 * @return
	 */
	public static SqlSessionHolder getSqlSessionHolder (SqlSessionFactory factory) {
		Map<SqlSessionFactory, SqlSessionHolder> map = threadLocal.get();
		
		if (map == null) {
			map = new HashMap<>();
			map.put(factory, new SqlSessionHolder(factory.openSession()));
			threadLocal.set(map);
		}
		
		SqlSessionHolder sqlSessionHolder = map.get(factory);
		
		if (sqlSessionHolder == null) {
			sqlSessionHolder = new SqlSessionHolder(factory.openSession());
		}
		
		return sqlSessionHolder;
	}
	
	/**
	 * 移除线程 ThreadLocal 中的 SqlSessionHolder
	 * @param factory
	 */
	public static void removeSqlSessionHolder (SqlSessionFactory factory) {
		Map<SqlSessionFactory, SqlSessionHolder> map = threadLocal.get();
		if (map != null) {
			map.remove(factory);
		}
	}
	
	public static Client getClient () {
		return clientSockets.get();
	}
	
	public static void setClient (Client client) {
		clientSockets.set(client);
	}
	
	/**
	 * 在执行完 Controller 中的方法后将 delayResponse 发送给指定客户端列表
	 * 其 requestClassName 为 执行完当前 Controller 时后要用到的的 requestClassName
	 * @param delayResponse
	 * @param delayResponseClientList
	 */
	public static void delayResponse (String responseData, List<Client> delayResponseClientList) {
		getClient().setDelayResponse(responseData);
		if (getClient().getDelayResponseClientList() != null) {
			getClient().getDelayResponseClientList().addAll(delayResponseClientList);
		} else {
			getClient().setDelayResponseClientList(delayResponseClientList);
		}
	}
	
	/**
	 * 在执行完 Controller 中的方法后将 delayResponse 发送给指定客户端
	 * 其 requestClassName 为 执行完当前 Controller 时后要用到的 requestClassName
	 * @param delayResponse
	 * @param delayResponseClient
	 */
	public static void delayResponse (String responseData, Client delayResponseClient) {
		List<Client> list = new ArrayList<>();
		list.add(delayResponseClient);
		delayResponse(responseData, list);
	}
}
